package com.hea7en.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hea7en.model.common.dto.ResponseResult;
import com.hea7en.model.common.enums.AppHttpCodeEnum;
import com.hea7en.model.user.dto.LoginDto;
import com.hea7en.model.user.pojo.ApUser;
import com.hea7en.user.mapper.UserMapper;
import com.hea7en.user.service.UserService;
import com.hea7en.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

/**
 * @author: hea7en
 * @Date: 2024/8/17 3:25 PM
 * @Description: 用户服务接口实现类
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,ApUser> implements UserService {
    @Override
    public ResponseResult login(LoginDto loginDto) {
        // 正常登录，手机号+密码
        if (StringUtils.isNotBlank(loginDto.getPhone())
                && StringUtils.isNotBlank(loginDto.getPassword())) {
            // 查询用户信息
            ApUser user = this.lambdaQuery().eq(ApUser::getPhone, loginDto.getPhone()).one();
            if (user==null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户信息不存在");
            }
            // 校验密码
            String salt = user.getSalt();
            String password = loginDto.getPassword();
            String psw = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            // 密码不正确
            if (!StringUtils.equals(psw, user.getPassword())) {
               return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            // 封装返回数据，携带jwt令牌
            HashMap<String, Object> data = new HashMap<>(12);
            data.put("token", AppJwtUtil.getToken(user.getId().longValue()));
            // 敏感信息置空
            user.setSalt("");
            user.setPassword("");
            data.put("user", user);
            return ResponseResult.okResult(data);
        }

        // 游客登录
        HashMap<String, Object> data = new HashMap<>(12);
        data.put("token", AppJwtUtil.getToken(0L));
        return ResponseResult.okResult(data);
    }
}
